﻿<template>
  <div>
    <el-table
      v-loading="isLoading"
      :data="companyList"
      :key="'company_list_'+type"
      tooltip-effect="dark"
      @row-click="handleClickRow"
      style="width: 100%"
      border
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column key="index" label="序号" type="index" align="center" width="50"></el-table-column>
      <el-table-column prop="name" show-overflow-tooltip label="单位名称" />
      <el-table-column prop="shortName" show-overflow-tooltip width="100" label="单位简称" />
      <el-table-column prop="code" show-overflow-tooltip key="code" label="编码" width="120" align="center" />
      <el-table-column prop="typeName" show-overflow-tooltip width="120" label="单位类型" />
      <el-table-column prop="stockPercent" show-overflow-tooltip width="60" label="股比" >
        <template slot-scope="item">
          {{item.row.stockPercent}}%
        </template>
      </el-table-column>
      <el-table-column prop="flag" show-overflow-tooltip width="50" align="center" label="启用" />

      <el-table-column key="option" align="left" width="300" label="操作">
        <template slot="header" >
          <el-button v-if="checkPermission('office:create')&&$store.state.user.companyId=='0'" type="primary" size="mini" @click="openAddDlg">新增</el-button>
          <el-button v-if="checkPermission('sys_office:sync')" type="primary" size="mini" @click="syncOffice">同步组织机构</el-button>
        </template>
        <template slot-scope="item">
          <el-button v-if="checkPermission('office:create')" size="mini" @click="openAddDlg(item.row)">添加子级
          </el-button>
          <el-button v-if="checkPermission('office:update')" size="mini" @click="openEditDlg(item.row)">编辑
          </el-button>
          <el-button v-if="!item.row.children&&checkPermission('office:delete')" type="danger" size="mini" @click="del(item.row.id)">删除
          </el-button>
          <!--          <el-button type="danger" size="medium" @click="del(projectInfo.row.id)">删除</el-button>-->
<!--          <el-button size="small" @click="openEditDlg(item.row)">编辑</el-button>-->
          <!--          <el-button size="medium" @click="openEditDlg(item.row)">权限设置</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align:center;padding-top:10px;"
      background
      layout="prev, pager, next"
      :total="totalPage"
    ></el-pagination>
    <el-dialog
      :title="company.id?'更新信息':'新建信息'"
      :visible.sync="companyDlgVisible"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-form
        label-width="auto"
        :model="company"
        :rules="rules"
        ref="ruleForm"
        style="width:100%;margin-top:20px;"
      >
        <el-col :span="24" v-if="company.parentName">
          <el-form-item label="公司名称:" prop="parentName">
            <el-input v-model="company.parentName" autocomplete="off" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位名称:" prop="name">
            <el-input v-model="company.name" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位简称:" prop="shortName">
            <el-input v-model="company.shortName" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位编码:" prop="code">
            <el-input v-model="company.code" autocomplete="off" :disabled="company.id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="company.parentId">
          <el-form-item label="单位类型:" prop="type">
            <meta-select type="office-type" placeholder="请选择单位类型" v-model="company.type" ></meta-select>
<!--            <el-select filterable default-first-option placeholder="请选择单位类型" v-model="company.type">-->
<!--              <el-option-->
<!--                v-for="item in typeList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id"-->
<!--              ></el-option>-->
<!--            </el-select>-->
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="company.type =='holding'||company.type =='share_participation'">
          <el-form-item label="股比(%):">
            <el-input v-model="company.stockPercent" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="company.id">
          <el-form-item label="是否废弃:">
            <template>
              <el-radio-group v-model="company.delFlag">
                <el-radio
                  size="small"
                  label="0"
                  border
                  style="background-color:white;margin-right:0;"
                >启用</el-radio>
                <el-radio size="small" label="1" border style="background-color:white;">废弃</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="saveCompany('ruleForm')">保存</el-button>
        <el-button @click="companyDlgVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import MetaSelect from "../../components/meta-select.vue";

export default {
  components: {MetaSelect},
  $$route:{
    meta:{
      title:'组织机构'
    }
  },
  name: "CompanyList",
    data() {
    return {
      isLoading: false,
      rules: {
        name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
        shortName: [
          { required: true, message: "请输入公司简称", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入公司编码", trigger: "blur" }],
       // type: [{ required: true, message: "请选择公司类型", trigger: "blur" }],
      },
      companyList: [],
      companyDlgVisible: false,
      company: {},
      totalPage: 1,
    };
  },
  computed: {},
  created: function () {
    if (this.$route.params.type && this.$route.params.type.length > 0) {
      this.type = this.$route.params.type;
    }
    this.loadCompanyList();
  },
  methods: {
    syncOffice(){
      this.isLoading = true;
      this.$post('/sso/sync/office',{},(res)=>{
        this.$message.success("同步完成")
        this.loadCompanyList();
      },()=>{
        this.isLoading = false;
      })
    },
    openAddDlg(parent) {
      this.company = {};
      if(parent) {
        this.company.parentId = parent.id;
        this.company.parentName = parent.name;
      } else {
      }
      this.companyDlgVisible = true;
    },
    openEditDlg(item) {
      this.company = {};
      this.companyDlgVisible = true;
      this.company = JSON.parse(JSON.stringify(item));
      this.company.editMode = true;
    },
    saveCompany: function (ruleForm) {
      const message = this.$message;
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (this.company.id) {
            this.$post("/company/update", this.company, (data) => {
              this.companyDlgVisible = false;
              message.success("更新成功！");
              this.loadCompanyList();
            });
          } else {
            this.$post("/company/create", this.company, (data) => {
              this.companyDlgVisible = false;
              message.success("创建成功！");
              this.loadCompanyList();
            });
          }
        }
      });
    },

    del: function (id) {
      this.$confirm('该操作同时移除子机构，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isLoading = true;
        this.$post("/company/delete", {id:id}, (data) => {
          this.$message.success('删除成功！');
          this.loadCompanyList();
        },(response)=>{
          this.isLoading = false;
        });
      }).catch(() => {
      });

    },


    handleClickRow(row, column, event) {},

    // appendDepartment(company) {
    //   if(company.children) {
    //     for (let item of company.children) {
    //       this.appendDepartment(item);
    //     }
    //   }
    //   if(company.officeList && company.officeList.length>0) {
    //     if(!company.children) {
    //       company.children = [];
    //     }
    //     for(let item of company.officeList) {
    //       company.children.push(item);
    //     }
    //
    //   }
    // },
    loadCompanyList() {
      this.isLoading = true;
      this.$get(
        "/company/tree",
        {},
        (data) => {
          let list = data.data;
          // for(let item of list) {
          //   this.appendDepartment(item);
          // }
          this.traverseTree(list)
          this.companyList = list;
        },
        () => {
          this.isLoading = false;
        }
      );
    },
    traverseTree(tree) {
      // 使用递归遍历树结构，添加部门子级
      function traverse(node) {
        if(node.officeList&&node.officeList.length>0) {
          if(!node.children){
            node.children = [];
          }
          node.children.push(...node.officeList);
          node.children.sort((a, b) => {
            if(isNaN(a.sort)||isNaN(b.sort)) {
              return 0;
            }
            return a.sort - b.sort;
          })
        }
        // 遍历子节点
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            traverse(child);
          });
        }
      }

      // 从根节点开始遍历
      tree.forEach(rootNode => {
        traverse(rootNode);
      });
    }
  },
};
</script>
